﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Diagnostics;
using Fly.Common.Log;
using RN.ERP.Web.BzkModelService;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// MergeProjectHandler 的摘要说明
    /// </summary>
    public class MergeProjectHandler : IHttpHandler
    {
        private RN.ERP.Web.ProjectService.ProjectServiceClient client = new ProjectService.ProjectServiceClient();
        public void ProcessRequest(HttpContext context)
        {
            GetParams(context);
        }

        #region 页面数据操作
        /// <summary>
        /// 获取传递参数
        /// </summary>
        private void GetParams(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["act"];
            string userguid = context.Request["userguid"];
            string username = context.Request["username"];
            string proName = context.Request["proName"];
            string proCode = context.Request["proCode"];
            string proID = context.Request["proID"];
            string proTitle = context.Request["proTitle"];
            string selectIds = context.Request["selectIds"];
            string fromStr = context.Request["fromStr"];
            string toStr = context.Request["toStr"];
            string hisStr = context.Request["hisStr"];

            string rst = string.Empty;
            switch (action.ToLower())
            {
                case "getmergepro":
                    rst = GetMergeProjectList(proName, proCode, context);
                    break;
                case "mergepro":
                    rst = MergeProjectByStr(fromStr, toStr, userguid, username);
                    break;
                case "getmergeprohistory":
                    rst = GetMergeProjectHistoryList(proName, userguid, context);
                    break;
                case "cancelmergepro":
                    rst = CancelMergeProject(hisStr, userguid, username);
                    break;
                case "getnamebycode":
                    rst = GetProjectByCode(proCode);
                    break;
            }
            context.Response.Write(rst);
        }

        #endregion

        /// <summary>
        /// 获取合并项目信息
        /// </summary>
        /// <param name="proName"></param>
        /// <returns></returns>
        public string GetMergeProjectList(string proName, string proCode, HttpContext context)
        {
            int total = 0;
            //if (string.IsNullOrEmpty(proName) && string.IsNullOrEmpty(proCode))
            //    return "";
            string conditions = GetMergeProjectConditions(proName, proCode);

            string mergeProStr = client.GetMergeProjectList(out total, 0, 1000, conditions);
            IList<h_projectBzk_NewExt> mergeList = JsonConvert.DeserializeObject<IList<h_projectBzk_NewExt>>(mergeProStr);
            var result = mergeList.Select(r => new MergeProject()
            {
                ID = r.ID,
                Title = r.Title,
                Code = r.Code,
                Address = r.Address,
                Owner = r.Owner,
                BidCount = r.BidCount,
            });

            string res = JsonConvert.SerializeObject(result);
            return res;
        }

        private string GetMergeProjectConditions(string proName, string proCode)
        {
            h_projectBzk_NewExt project = new h_projectBzk_NewExt();
            project.Title = proName;
            project.Code = proCode;
            string conditions = JsonConvert.SerializeObject(project);
            return conditions;
        }

        /// <summary>
        /// 项目合并
        /// </summary>
        /// <param name="fromStr"></param>
        /// <param name="toStr"></param>
        /// <returns></returns>
        private string MergeProjectByStr(string fromStr, string toStr, string userguid, string username)
        {
            string rst = string.Empty;
            int[] fromArr = TranArrFromStrToInt(fromStr);
            int[] toArr = TranArrFromStrToInt(toStr);

            if (fromArr.Length < 1 || toArr.Length < 1)
            {
                rst = "至少添加一个！";
            }
            else if (toArr.Length > 1)
            {
                rst = "目标列只能添加一个！";
            }
            else
            {
                //Stopwatch sw = new Stopwatch();
                //sw.Start();
                bool b = client.MergeProjects(fromArr, toArr[0], 1, userguid, username);
                //  sw.Stop();
                //  LogWriter.WriteInfo("fromProjects:" + fromArr + ",toProjects:" + toArr[0] + ",bKind:1" + "用时：" + sw.ElapsedMilliseconds, "合并操作");
                if (b)
                    rst = "合并成功！";
                else
                    rst = "合并失败！";
            }

            return rst;
        }

        private int[] TranArrFromStrToInt(string str)
        {
            if (str.EndsWith(","))
                str = str.TrimEnd(',');
            string[] strArr = str.Split(',');

            int[] intArr = new int[strArr.Length];
            for (int i = 0; i < strArr.Length; i++)
            {
                int.TryParse(strArr[i], out intArr[i]);
            }

            return intArr;
        }

        /// <summary>
        /// 获取合并历史
        /// </summary>
        /// <param name="proName"></param>
        /// <returns></returns>
        private string GetMergeProjectHistoryList(string proName, string userguid, HttpContext context)
        {
            int total = 0;

            string conditions = string.Format("{0},{1}", proName, userguid);
            string mergeProStr = client.GetMergeProjectHistoryList(out total, 0, 10000, conditions);

            IList<h_projectbzk_ProjectMergeHistory> mergeHistoryList =
                JsonConvert.DeserializeObject<IList<h_projectbzk_ProjectMergeHistory>>(mergeProStr);
            var result = mergeHistoryList.Select(r => new MergeProjectHistory()
            {
                ID = r.ID,
                FromProjectID = r.FromProjectID,
                FromProjectName = r.FromProjectName,
                ToProjectID = r.ToProjectID,
                ToProjectName = r.ToProjectName,
                bKind = r.bKind,
                GroupID = r.GroupID,
                UpdateTime = r.UpdateTime,
                CreateManName = r.CreateManName,
                bCancel = r.bCancel
            });

            string res = JsonConvert.SerializeObject(result);
            return res;
        }

        /// <summary>
        /// 撤销项目
        /// </summary>
        /// <param name="hisStr"></param>
        /// <returns></returns>
        private string CancelMergeProject(string hisStr, string userguid, string username)
        {
            string rst = string.Empty;
            int[] hisArr = TranArrFromStrToInt(hisStr);
            bool b = client.CancelMergeProjects(hisArr, userguid, username);
            if (b)
                rst = "撤销成功";
            else
                rst = "撤销失败";

            return rst;
        }

        /// <summary>
        /// 根据code找名字
        /// </summary>
        /// <param name="proCode"></param>
        /// <returns></returns>
        private string GetProjectByCode(string proCode)
        {
            string name = string.Empty;
            string areaCode = System.Configuration.ConfigurationManager.AppSettings["SysAreaCode"];
            if (!string.IsNullOrEmpty(proCode))
            {
                string proStr = client.GetProjectByCode(proCode, areaCode);
                h_projectBzk_NewExt pro = JsonConvert.DeserializeObject<h_projectBzk_NewExt>(proStr);
                name = pro.Title;
            }
            return name;
        }



        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region 返回实体
        private class MergeProject
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public string Code { get; set; }
            public string Address { get; set; }
            public string Owner { get; set; }
            public int? BidCount { get; set; }
            public int MenuID { get; set; }
        }

        private class MergeProjectHistory
        {
            public Int32 ID { get; set; }
            public Int32? FromProjectID { get; set; }
            public String FromProjectName { get; set; }
            public Int32? ToProjectID { get; set; }
            public String ToProjectName { get; set; }
            public Byte? bKind { get; set; }
            public Int32? GroupID { get; set; }
            public DateTime? CreateTime { get; set; }
            public DateTime? UpdateTime { get; set; }
            public String CreateManName { get; set; }
            public Boolean? bCancel { get; set; }
        }

        #endregion
    }
}